﻿using System;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Reflection;
using CustomORM.DataAccess;
using CustomORM.Mapping;
using NUnit.Framework;

namespace CustomORM.Tests.IntegrationTests
{
    [TestFixture]
    public class BaseTestDAL
    {
        static BaseTestDAL()
        {
            // If you have your entities mapping setup in another project to CustomORM, than you should add this at the start
            // of your application
            MagicMapper.RemoveAllMappers();
            MagicMapper.ScanForMappers(Assembly.GetExecutingAssembly());
        }

        public string ConnectionString = string.Empty;
        public string ProviderName = string.Empty;
        public string SelectCustomerSql = "select top 1 * from Customers";
        
        public int GetSomethingCommonForAllTests()
        {
            if(string.IsNullOrEmpty(ConnectionString))
            {
                Assert.Fail("Please run BaseTestDAL.SetUp to initialize ConnectionString, before calling GetSomethingCommonForAllTests.");
            }

            var sqlServerDataAccess = new AdoDataAccess(ConnectionString, ProviderName);

            var dataTable = sqlServerDataAccess.SelectSQL(SelectCustomerSql);

            using (DataTableReader dr = dataTable.CreateDataReader())
            {
                if (dr.Read())
                {
                    return (int)dr["CustomerID"];
                }

                Assert.Ignore("Cannot run Unit Test, as database has no customers at all.");
                // execution of test will stop, but we want to make this method to compile :)
                return -1;
            }
        }

        [TestFixtureSetUp]
        public void SetUp()
        {
            try
            {
                var connectionStringSettings = ConfigurationManager.ConnectionStrings["ConnectionString"];
                if(connectionStringSettings != null)
                {
                    ConnectionString = connectionStringSettings.ConnectionString;
                    ProviderName = connectionStringSettings.ProviderName;                    
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Failed to get connection string.");
                throw;
            }
        }
    }
}